//
//  BindPhoneViewController.m
//  ShowYork
//
//  Created by hxh on 2020/11/20.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "BindPhoneViewController.h"
#import "LoginViewController.h"
#import "TabBarViewController.h"
#import "LoginAndRegisterTitleView.h"

#import "UserInfoFollowModel.h"
@interface BindPhoneViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)UIImageView *loginBackGroundImgView;
@property (nonatomic,strong)UIButton *backButton;
/// 标题
@property (nonatomic,strong)LoginAndRegisterTitleView *titleView;
@property (nonatomic,strong)UIView *phoneView;
/// 输入框
@property (nonatomic,strong)UITextField *phoneTF;
@property (nonatomic,strong)UILabel *phonePlaceLb;

@property (nonatomic,strong)UIView *codeView;
/// 输入框
@property (nonatomic,strong)UITextField *codeTF;

@property (nonatomic,strong)UILabel *codePlaceLb;
/// 按钮
@property (nonatomic,strong)UIButton *loginBtn;

@property (nonatomic,strong)UIButton *sendCodeBtn;

@end

@implementation BindPhoneViewController


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHideNavBar = YES;
    [self setUI];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    [self.view addSubview:self.loginBackGroundImgView];
    [self.view addSubview:self.backButton];
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.phoneView];
    [self.view addSubview:self.phoneTF];
    [self.view addSubview:self.phonePlaceLb];
    [self.view addSubview:self.codeView];
    [self.view addSubview:self.codeTF];
    [self.view addSubview:self.codePlaceLb];
    [self.view addSubview:self.loginBtn];
    [self.view addSubview:self.sendCodeBtn];

    self.loginBackGroundImgView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(16 + GK_STATUSBAR_HEIGHT);
        make.left.equalTo(self.view.mas_left).offset(16);
    }];
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backButton.mas_bottom).offset(28);
        make.right.equalTo(self.view.mas_right).offset(-24);
        make.left.equalTo(self.view.mas_left).offset(24);
    }];
    
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleView.mas_bottom).offset(40);
        make.height.mas_equalTo(44);
        make.right.equalTo(self.view.mas_right).offset(-16);
        make.left.equalTo(self.view.mas_left).offset(16);
    }];
    [self.phonePlaceLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.phoneView);
        make.left.equalTo(self.phoneView).offset(20);
    }];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.phoneView).offset(20);
        make.centerY.equalTo(self.phoneView);
        make.right.equalTo(self.phoneView.mas_right).offset(-20);
    }];
    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneView.mas_bottom).offset(28);
        make.height.mas_equalTo(44);
        make.right.equalTo(self.view.mas_right).offset(-16);
        make.left.equalTo(self.view.mas_left).offset(16);
    }];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.codeView).offset(20);
        make.centerY.equalTo(self.codeView);
        make.right.equalTo(self.codeView.mas_right).offset(-20);
    }];
    [self.codePlaceLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.codeView);
        make.left.equalTo(self.codeView).offset(20);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeView.mas_bottom).offset(28);
        make.height.mas_equalTo(44);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
    }];
    [self.sendCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.codeView);
        make.top.bottom.equalTo(self.codeView);
        make.right.equalTo(self.codeView).offset(-20);
    }];
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)loginMethod{
    /*
     phone      |string         |手机号码
     phoneCode  |string         |验证码
     nickName   | string        |用户名
     avatar     | string        |用户头像
     type       | int           |1:微信 2:QQ 3:微博
     openId     |string         |第三方openId
     md5        |string         |md5加密
     */
    [SVProgressHUD show];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:ThirdBind];
    param[@"phone"] = self.phoneTF.text;
    param[@"phoneCode"] = self.codeTF.text;
    if (self.otherLoginModel.name.length != 0) {
        param[@"nickName"] = self.otherLoginModel.name;
    }
    if (self.otherLoginModel.iconurl.length != 0) {
        param[@"avatar"] = self.otherLoginModel.iconurl;
    }
    param[@"type"] = self.otherLoginModel.type;
    param[@"openId"] = self.otherLoginModel.openid;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(ThirdBind) parames:param success:^(id responseObj) {
        NSNumber *userId = responseObj[RESPONSE][@"id"];
        BOOL isNew = [responseObj[RESPONSE][@"isNew"] boolValue];
        if (isNew) {
            [self getUserInfoById:userId];
        }else{
            NSString *typeName = @"苹果帐号";
            if (self.otherLoginModel.type.intValue == 1) {
                typeName = @"微信帐号";
            }else if (self.otherLoginModel.type.intValue == 2) {
                typeName = @"QQ帐号";
            }
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"该手机号已注册，是否将此%@与该手机号绑定？",typeName] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alertController dismissViewControllerAnimated:YES completion:nil];
                [self updateOpenIdByUserId:userId];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [WHToast showMessage:@"请用已注册手机号登录" duration:2 finishHandler:nil];
                [alertController dismissViewControllerAnimated:YES completion:nil];
                [self.navigationController popViewControllerAnimated:YES];
               
            }];
            //往alertViewController上添加alertAction
            [alertController addAction:cancelAction];
            [alertController addAction:confirmAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
    
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)updateOpenIdByUserId:(NSNumber *)userId{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:UpdateOpenId];
    param[@"id"] = userId;
    param[@"type"] = self.otherLoginModel.type;
    param[@"openId"] = self.otherLoginModel.openid;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateOpenId) parames:param success:^(id responseObj) {
        [self getUserInfoById:userId];
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)getUserInfoById:(NSNumber *)userId{
    // 请求用户登录信息
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = userId;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUser];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUser) parames:param success:^(id responseObj) {
        UserInfoModel *userInfo = [UserInfoModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        [userInfo save];
   
        [self getUserFollowListSource];

    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    
    }];
}

- (void)getUserFollowListSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetFollowList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetFollowList) parames:param success:^(id responseObj) {

        NSArray *resultArray = [UserInfoFollowModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        
        // 获取数据库单例对象
        RLMRealm *realm = [RLMRealm defaultRealm];
        // 更新当前登录这样用户的信息
        [realm transactionWithBlock:^{
            [realm addOrUpdateObjects:resultArray];
        }];
        
        __weak typeof(self)weakSelf = self;
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"登录成功" originY:0 duration:1 finishHandler:^{
            if (weakSelf.isAppLogin) {
                TabBarViewController *tabbarVC = [[TabBarViewController alloc]init];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabbarVC;
            }else{
                __block NSInteger index = -1;
                [weakSelf.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isKindOfClass:[LoginViewController class]]) {
                        index = idx;
                        *stop = YES;
                    }
                }];
                
                if (index != -1) {
                    [weakSelf.navigationController popToViewController:weakSelf.navigationController.viewControllers[index - 1] animated:NO];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfoSource" object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfoUseage" object:nil];
                    // 发送通知 刷新页面按钮状态
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLoginUserInfoFollowListStatus" object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateRefreshToken" object:nil];
                }
            }
            [MobClick event:@"login_phone"];
        }];

    } failure:^(id error) {

    }];
}

- (void)sendCodeMethod{
    
    self.sendCodeBtn.userInteractionEnabled = NO;
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.phoneTF.text;
    param[@"md5"] = [RPAppManager md5StrWithApi:SendCode];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SendCode) parames:param success:^(id responseObj) {
        __block NSInteger time = 59;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(timer, ^{
            if (time <= 0) {
                dispatch_source_cancel(timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.sendCodeBtn.enabled = YES;
                    self.sendCodeBtn.userInteractionEnabled = YES;
                    [self.sendCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                });
            }else{
                int seconds = time % 60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%.2d秒",seconds] forState:UIControlStateDisabled];
                    self.sendCodeBtn.enabled = NO;
                });
                time--;
            }
        });
        dispatch_resume(timer);
        
    } failure:^(NSError *error) {
        self.sendCodeBtn.userInteractionEnabled = YES;
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

#pragma mark - textDidChange
- (void)textDidChange:(UITextField *)textField{
    if (textField == self.phoneTF) {
        self.phonePlaceLb.hidden = textField.text.length > 0;
        if (textField.text.length > 11) {
            textField.text = [textField.text substringWithRange:NSMakeRange(0, 11)];
        }
        if (textField.text.length == 11 && [[textField.text substringToIndex:1] isEqualToString:@"1"]) {
            self.sendCodeBtn.enabled = YES;
        }else{
            self.sendCodeBtn.enabled = NO;
        }
    }
    if (textField == self.codeTF) {
        self.codePlaceLb.hidden = textField.text.length > 0;
        if(textField.text.length > 6){
            textField.text = [textField.text substringToIndex:6];
        }
    }
    
    if (self.codeTF.text.length > 0 && self.phoneTF.text.length == 11) {
        self.loginBtn.highlighted = YES;
        self.loginBtn.enabled = YES;
    }else{
        self.loginBtn.highlighted = NO;
        self.loginBtn.enabled = NO;
    }
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    return YES;
}

#pragma mark - lazy
- (UIImageView *)loginBackGroundImgView{
    if (!_loginBackGroundImgView) {
        _loginBackGroundImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_backgroud_tag"]];
    }
    return _loginBackGroundImgView;
}
- (UIButton *)backButton{
    if (!_backButton) {
        _backButton = [[UIButton alloc]init];
        [_backButton setImage:[UIImage imageNamed:@"common_back_normal_tag"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}
- (LoginAndRegisterTitleView *)titleView{
    if (!_titleView) {
        _titleView = [[LoginAndRegisterTitleView alloc]initWithMainTitle:@"绑定手机号" andSubTitle:@"应《中华人民共和国网络安全法》要求，为了更好保障您的帐号安全，请绑定您的手机号"];
    }
    return _titleView;
}

- (UILabel *)phonePlaceLb{
    if (!_phonePlaceLb) {
        _phonePlaceLb = [[UILabel alloc]init];
        _phonePlaceLb.text = @"请输入手机号";
        _phonePlaceLb.textColor = RGBA(204, 204, 204, 1);
        _phonePlaceLb.font = font(14);
    }
    return _phonePlaceLb;
}

- (UILabel *)codePlaceLb{
    if (!_codePlaceLb) {
        _codePlaceLb = [[UILabel alloc]init];
        _codePlaceLb.text = @"请输入短信验证码";
        _codePlaceLb.textColor = RGBA(204, 204, 204, 1);
        _codePlaceLb.font = font(14);
    }
    return _codePlaceLb;
}


- (UITextField *)phoneTF{
    if (!_phoneTF) {
        _phoneTF = [[UITextField alloc]init];
        _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
        [_phoneTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        _phoneTF.returnKeyType = UIReturnKeyDone;
        _phoneTF.textColor = [UIColor whiteColor];
        _phoneTF.font = font(14);
        _phoneTF.delegate = self;
        [_phoneTF becomeFirstResponder];
    }
    return _phoneTF;
}

- (UIView *)phoneView{
    if (!_phoneView) {
        _phoneView = [[UIView alloc]init];
        _phoneView.backgroundColor = RGBA(255, 255, 255, 0.2);
        _phoneView.layer.cornerRadius = 22;
        _phoneView.layer.masksToBounds = YES;
    }
    return _phoneView;
}

- (UITextField *)codeTF{
    if (!_codeTF) {
        _codeTF = [[UITextField alloc]init];
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
        [_codeTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        _codeTF.returnKeyType = UIReturnKeyDone;
        _codeTF.textColor = [UIColor whiteColor];
        _codeTF.font = font(14);
        _codeTF.delegate = self;
        if (@available(iOS 12.0, *)) {
            _codeTF.textContentType = UITextContentTypeOneTimeCode;
        } else {
            // Fallback on earlier versions
        }
    }
    return _codeTF;
}

- (UIView *)codeView{
    if (!_codeView) {
        _codeView = [[UIView alloc]init];
        _codeView.backgroundColor = RGBA(255, 255, 255, 0.2);
        _codeView.layer.cornerRadius = 22;
        _codeView.layer.masksToBounds = YES;
    }
    return _codeView;
}

- (UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc]init];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_normal_tag"] forState:UIControlStateNormal];
        [_loginBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_selected_tag"] forState:UIControlStateHighlighted];
        
        [_loginBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateNormal];
        [_loginBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateHighlighted];
//        [_codeBtn setBackgroundImage:[UIImage imageNamed:@"login_bg_tag"] forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginMethod) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.enabled = NO;
    }
    return _loginBtn;
}
- (UIButton *)sendCodeBtn{
    if (!_sendCodeBtn) {
        _sendCodeBtn = [[UIButton alloc]init];
        [_sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_sendCodeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_sendCodeBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateDisabled];
        [_sendCodeBtn addTarget:self action:@selector(sendCodeMethod) forControlEvents:UIControlEventTouchUpInside];
        _sendCodeBtn.titleLabel.font = font(10);
        _sendCodeBtn.enabled = NO;
    }
    return _sendCodeBtn;
}



@end
